<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/10/12
 * Time: 上午10:17
 */

namespace app\activity\logic;


use app\model\ActivityCollectionPoint;
use app\model\ActivityGroupStage;
use app\model\ActivityOrder;
use extend\Functions;
use extend\STATUS_CODE;
use think\Db;

class Activity
{
    /**
     * @purpose 集合点列表统计
     * @param int $group_stage_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function collectionPointTravelByGroupStage (int $group_stage_id): array
    {
//        $group_stage = new ActivityGroupStage();
        $collection_point = new ActivityCollectionPoint();
        $result  = $collection_point
            ->with(['orderAttach' => function($query) {
                $query
                    ->where('oa.status', 99)
                    ->alias('oa')
                    ->join(ActivityOrder::M()->table.' ao', 'oa.order_id=ao.id')
                    ->leftJoin(\app\model\Member::M()->table.' m', 'm.uid=ao.uid')
                    ->order('ao.pay_time asc')
                    ->field('oa.id,oa.fullname,oa.travel_sex,oa.collection_point_id,oa.travel_mobile,m.nickname,m.username');
            }])
            ->where('activity_group_stage_id', $group_stage_id)
            ->field('id,city_name,title,address')
            ->select();
        foreach ($result as &$travels) {
            foreach ($travels['order_attach'] as &$travel) {
                $travel['fullname'] = Functions::hideNameSecond($travel['fullname']);
                $travel['travel_mobile'] = Functions::hide_mobile($travel['travel_mobile']);
                unset($travel['collection_point_id']);
            }
        }
        return Functions::result($result);
    }
    /**
     * @purpose 获取活动详情
     * @param int $group_stage_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public static function detail(int $group_stage_id): array
    {
        if (!$group_stage_id) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误'
            );
        }
        $group_stage      = new ActivityGroupStage();
        $collection_point = new ActivityCollectionPoint();
        $fields           = 'gs.id,gs.activity_id,gs.can_sign_up,gs.apply_end_date as apply_end_time,
        FROM_UNIXTIME(gs.start_time, "%m月%d日") as start_date,start_time,
        FROM_UNIXTIME(gs.apply_end_date, "%m月%d日 %H:%i") as apply_end_date,
        gs.adult_price,gs.kid_price,gs.insurance_type,gs.insurance_price,
        (FLOOR(((gs.end_time - gs.start_time) / 86400)) + 1) as days,
        a.title,a.difficulty,a.descriptions,a.slider,a.thumb,a.way_type,a.light_spot,a.graphic,
        a.leader_graphic,a.trip_graphic,a.activity_notice,a.club_id,cb.name as club_name,a.destination,
        (select count(1) from activity_order_attach where `status` = 99 and `group_stage_id`=`gs`.`id`) as sign_up_num,
        (select sum(sign_up_limit) as sign_up_limit from activity_collection_point where activity_group_stage_id=gs.id) as sign_up_limit';
        // 获取基础信息
        $activity_info = $group_stage
            ->alias('gs')
            ->join('activity a', 'gs.activity_id=a.id')
            ->join('club cb', 'a.club_id=cb.uid')
            ->where('gs.id', $group_stage_id)
            ->field($fields)
            ->find();
        if (!$activity_info) {
            return Functions::result(
                STATUS_CODE::DATA_NOT_FIND,
                '活动不存在或已过期...!'
            );
        }
        $activity_info->start_date = $activity_info->start_date . ' ' . Functions::getTimeWeek($activity_info->start_time);
        $activity_info->light_spot = json_decode($activity_info->light_spot);
        $activity_info->slider     = json_decode($activity_info->slider);
        $activity_info->overdue_sign_up = ($activity_info->apply_end_time < time());
        // 所有团期
        $fields           = 'id,FROM_UNIXTIME(start_time, "%Y-%m-%d") as start_date,start_time,
        FROM_UNIXTIME(apply_end_date, "%m月%d日 %H:%i") as apply_end_date,
        adult_price,kid_price,insurance_type,insurance_price,
        (select count(1) from activity_order_attach where `status` = 99 and `group_stage_id`=`gs`.`id`) as sign_up_num,
        (select sum(sign_up_limit) as sign_up_limit from activity_collection_point where activity_group_stage_id=gs.id) as sign_up_limit';
        $group_stage_item = $group_stage
            ->alias('gs')
            ->where([
                ['gs.activity_id', '=', $activity_info->activity_id],
                ['gs.start_time', '>', time()]
            ])
            ->field($fields)
            ->order('start_time asc')
            ->select();
        foreach ($group_stage_item as $key => $item) {
            $group_stage_item[$key]['week'] = Functions::getTimeWeek($item->start_time);
        }
        // 获取当前团期的集合点
        $collection_point_item = $collection_point
            ->where('activity_group_stage_id', $group_stage_id)
            ->field('id,title,address,lng,lat,FROM_UNIXTIME(set_out_time, "%H:%i") as set_out_date,set_out_time,sign_up_limit')
            ->select();
        foreach ($collection_point_item as $key => $item) {
            $collection_point_item[$key]['set_out_date'] = $item->set_out_date . ' ' . Functions::getTimeWeek($item->set_out_time);
        }
        $activity_info                     = $activity_info->toArray();
        $activity_info['group_stage']      = $group_stage_item;
        $activity_info['collection_point'] = $collection_point_item;
        return Functions::result($activity_info);
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function homeItems(
        $page = 1,
        $size = 20,
        $lng = 104.045522,
        $lat = 30.544916,
        $kw = ''): array
    {
        $model  = new ActivityGroupStage();
        $fields = [
            'gs.id' => 'group_stage_id',
            'gs.activity_id',
            'FROM_UNIXTIME(gs.start_time, "%m月%d日")' => 'start_date',
            'gs.start_time',
            'FROM_UNIXTIME(gs.apply_end_date, "%m月%d日 %H:%i")' => 'sign_up_end_date',
            'gs.adult_price',
            'gs.kid_price',
            'gs.can_sign_up',
            'gs.apply_end_date',
            'a.title',
            'a.difficulty',
            'a.thumb',
            'a.way_type',
            'a.light_spot',
            'a.club_id',
            'a.destination',
            '(select sum(sign_up_limit) as sign_up_limit from activity_collection_point where activity_group_stage_id=gs.id and delete_time = 0)' => 'sign_up_limit',
            '(select count(1) from activity_order_attach where `status` = 99 and `group_stage_id`=`gs`.`id`)' => 'sign_up_num',
            'cb.name' => 'club_name',
            '(ACOS(SIN('.$lat.' * 3.1415 / 180) * SIN(gs.lat * 3.1415 / 180) + COS('.$lat.' * 3.1415 / 180) * COS(gs.lat * 3.1415 / 180) * COS('.$lng.' * 3.1415 / 180 - gs.lng * 3.1415 / 180)) * 6380)' => 'distance'
        ];
        // 定义查询区域, 经度1度大概为85.39km 纬度1度大概为 111KM
        // 这里经度查询大概666公里范围， 纬度查询大概 512.34公里范围
        $scope = 3;
        $where = [];
        $where[] = ['gs.lat', '>', $lat - $scope];
        $where[] = ['gs.lat', '<', $lat + $scope];
        $where[] = ['gs.lng', '>', $lng - $scope];
        $where[] = ['gs.lng', '<', $lng + $scope];
        $subQuery = $model
            ->alias('gs')
            ->join('activity a', 'gs.activity_id=a.id')
            ->join('club cb', 'a.club_id=cb.uid')
            ->field($fields)
            ->where([
                ['gs.status', '=', 99],
                ['gs.start_time', '>', time()]
            ])
            ->where($where)
            ->buildSql();
        $subWhere = [];
        if ($kw) {
            $subWhere[] = ['s.title', ['like', '%'.$kw], ['like', '%'.$kw.'%'], ['like', $kw.'%'], 'or'];
        }
        $result = Db::table($subQuery.' s')
            ->page($page, $size)
            ->order('s.distance asc')
            ->where($subWhere)
            ->select();
        foreach ($result as $key => $value) {
            $result[$key]['overdue_sign_up'] = ($value['apply_end_date'] < time());
            $result[$key]['start_date'] = $value['start_date'] . ' (' . Functions::getTimeWeek($value['start_time']) . ')';
            $result[$key]['light_spot'] = json_decode($value['light_spot'], true);
        }
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
}